/**
 * @(#) ReqForOthersMediator.as
 *
 * @date		2009. 03. 06.
 * @version		1.0
 * @author		Shin, Yunwoo
 * @description	근무 - Mediator
 * 				근무관리 Presentation Logic을 관리 
 */
package com.skt.common_hr.teamworktime_sac.view
{
	import com.skt.common_hr.common.components.CommonAlert;
	import com.skt.common_hr.common.puremvc.CommonMediator;
	import com.skt.common_hr.teamworktime_sac.TeamWorkTimeFacade;
	import com.skt.common_hr.teamworktime_sac.model.ReqVacationProxy;
	import com.skt.common_hr.teamworktime_sac.model.ReqWorkTimeProxy;
	import com.skt.common_hr.teamworktime_sac.model.VacationCodeProxy;
	import com.skt.common_hr.teamworktime_sac.model.vo.MemberVO;
	import com.skt.common_hr.teamworktime_sac.model.vo.ReqVacationVO;
	import com.skt.common_hr.teamworktime_sac.view.components.ReqForOthersView;
	
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;
	import mx.managers.PopUpManager;
	
	import org.puremvc.as3.multicore.interfaces.INotification;
	
	public class ReqForOthersMediator extends CommonMediator
	{
		public static const NAME:String = "ReqForOthersMediator"; 

		
		/**
		* 생성자
		* 
		* @param
		* @return void
		*/
        public function ReqForOthersMediator( viewComponent:Object )
        {
            super( NAME, viewComponent );
            view.callLater(initView);
        }
 		
		/**
		* View를 초기화 한다.
		*	- View에 기본사항을 출력하고 data를 load
		* @param
		* @return void
		*/
 		private function initView():void
 		{
 			view.addEventListener("CHANGE_REQ_VACATION", onVacation);
 			view.addEventListener("CHANGE_REQ_WORKTIME", onWorkTime);
 			view.addEventListener(ReqForOthersView.ADD_VACATION_RECORD, onAddVacationRec);
 			view.addEventListener(ReqForOthersView.ADD_WORKTIME_RECORD, onAddWorkTimeRec);
 			view.addEventListener(ReqForOthersView.DEL_VACATION_RECORD, onDelVacationRec);
 			view.addEventListener(ReqForOthersView.DEL_WORKTIME_RECORD, onDelWorkTimeRec);
 			view.addEventListener(ReqForOthersView.CONFIRM_VACATION, onConfirmVacation);
 			view.addEventListener(ReqForOthersView.CONFIRM_WORKTIME, onConfirmWorkTime);
 			
 			
 			
 			
 			// 휴가 코드리스트를 가져온다.
 			var codeProxy:VacationCodeProxy = facade.retrieveProxy(VacationCodeProxy.NAME) as VacationCodeProxy;
			view.vacationCodeList = codeProxy.vacationList;
			view.worktimeCodeList = codeProxy.worktimeList;
			
			view.reqVacationList = new ArrayCollection();
			addVacationRecord(view.reqVacationList);
			view.reqWorkTimeList = new ArrayCollection();
			addWorkTimeRecord(view.reqWorkTimeList);
  		}
		
 		public function setMember(member:MemberVO):void
 		{
 			view.selectedMember=member;
 			view.reqVacationList = new ArrayCollection();
 			addVacationRecord(view.reqVacationList);
 			view.reqWorkTimeList = new ArrayCollection();
 			addWorkTimeRecord(view.reqWorkTimeList);
 			loadWorkCode();
 		}
		
		private function loadWorkCode():void
		{ 		
 			// 휴가 종류 코드를 로드한다.
  			var codeProxy:VacationCodeProxy = facade.retrieveProxy(VacationCodeProxy.NAME) as VacationCodeProxy;
 			codeProxy.load(view.selectedMember.PERNR);
		}
		
		private function onVacation(event:Event):void
 		{
 			view.vsReq.selectedIndex = 1;
 		}
 		
 		private function onWorkTime(event:Event):void
 		{
 			view.vsReq.selectedIndex = 0;
 		}


 		private function onAddVacationRec(event:Event):void
 		{
 			addVacationRecord(view.reqVacationList);
 		}
 		
		private function onAddWorkTimeRec(event:Event):void
 		{
 			addWorkTimeRecord(view.reqWorkTimeList);
 		}
 
		private function onDelVacationRec(event:Event):void
 		{
			for (var i:int=0; i<view.reqVacationList.length; i++)
			{
				if(view.reqVacationList.getItemAt(i).del) {
					view.reqVacationList.removeItemAt(i--);
				}
			} 			
			if(view.reqVacationList.length==0) {
				addVacationRecord(view.reqVacationList);
			}
 		}
 		
		private function onDelWorkTimeRec(event:Event):void
 		{
			for (var i:int=0; i<view.reqWorkTimeList.length; i++)
			{
				if(view.reqWorkTimeList.getItemAt(i).del) {
					view.reqWorkTimeList.removeItemAt(i--);
				}
			} 			
			if(view.reqWorkTimeList.length==0) {	// 모든 레코드를 삭제했으면, 빈 레코드하나를 추가한다.
	 			addWorkTimeRecord(view.reqWorkTimeList);
			}
 		}
 
 
 		private function addVacationRecord(arr:ArrayCollection):void
 		{
 			var vo:ReqVacationVO = new ReqVacationVO();
 			vo.selectedIndex = 0;
 			vo.BEGDA = new Date();
 			vo.ENDDA = new Date();
 			arr.addItem(vo);
 		}
 		
 		private function addWorkTimeRecord(arr:ArrayCollection):void
 		{
 			var vo:ReqVacationVO = new ReqVacationVO();
 			vo.selectedIndex = 0;
 			vo.BEGDA = new Date();
 			vo.BEGUZ = new Date();
 			vo.BEGUZ.hours = 18;
 			vo.BEGUZ.minutes = 0;
 			vo.BEGUZ.seconds = vo.BEGUZ.milliseconds = 0;
 			vo.ENDUZ = new Date();
 			vo.ENDUZ.hours = 18;
 			vo.ENDUZ.minutes = 0;
 			vo.ENDUZ.seconds = vo.ENDUZ.milliseconds = 0;
 			arr.addItem(vo);
 		}



		private function onConfirmVacation(event:Event):void
		{
 			var table:Array = new Array();
 			var i:int = 0;
 			for each(var src:ReqVacationVO in view.reqVacationList)
 			{
 				if(src.selectedIndex<=0) {
 					CommonAlert.showMessage(commonFacade.bundle, "휴가 종류를 선택하셔야 합니다.", null, "입력오류", view);
 					return;
 				}
 				if(Number(src.BEGDA) > Number(src.ENDDA)) {
 					CommonAlert.showMessage(commonFacade.bundle, "휴가종료일이 휴가시작일 보다 작습니다. \n휴가기간을 다시 조정해 주십시오.", null, "입력오류", view);
 					return;
 				}
 				if(!checkHoliday(src.BEGDA)) {
 					CommonAlert.showMessage(commonFacade.bundle, "휴일은 휴가를 신청할 수 없습니다.", null, "입력오류", view);
 					return;
 				}
 				src.SEQNO = (i++).toString();
 				src.PERNR = src.IPERNR = view.selectedMember.PERNR;
 				src.DGBN  = "1";
 				src.BEGUZ = null;
 				src.ENDUZ = null;
 				src.AWART = view.vacationCodeList.getItemAt(src.selectedIndex).code;
 				src.AWATX = view.vacationCodeList.getItemAt(src.selectedIndex).text;
 				if(src.AWART=="0120") // 반차
 				{
 					src.APM = (src.bAM==true) ? "A" : "P";
 					src.ENDDA = src.BEGDA;
 				}
 				table.push(src);
 			}
 			var proxy:ReqVacationProxy = facade.retrieveProxy(ReqVacationProxy.NAME) as ReqVacationProxy;
 			proxy.InsertVacation("2", table);
		}
		
 		private function checkHoliday(target:Date):Boolean
 		{
 			if(target.day==0 || target.day==6) {
 				return false;
 			}
			return  true;
 		}

		private function onConfirmWorkTime(event:Event):void
		{
 			var table:Array = new Array();
 			var i:int = 0;
 			for each(var src:ReqVacationVO in view.reqWorkTimeList)
 			{
 				if(src.selectedIndex<=0) {
 					CommonAlert.showMessage(commonFacade.bundle, "근태 종류를 선택하셔야 합니다.", null, "입력오류", view);
 					return;
 				}
 				src.SEQNO = (i++).toString();
 				src.AWART = view.worktimeCodeList.getItemAt(src.selectedIndex).code;
 				src.AWATX = view.worktimeCodeList.getItemAt(src.selectedIndex).text;
 				src.PERNR = src.IPERNR = view.selectedMember.PERNR;
 				src.DGBN  = "2";
 				src.ENDDA = new Date(src.BEGDA);
 				src.ENDUZ.fullYear = src.BEGUZ.fullYear = src.BEGDA.fullYear;
 				src.ENDUZ.month = src.BEGUZ.month = src.BEGDA.month;
 				src.ENDUZ.date  = src.BEGUZ.date  = src.BEGDA.date;
 				if(Number(src.BEGUZ) > Number(src.ENDUZ) ) {
 					trace(src.BEGUZ + ", " + src.ENDUZ);
 					CommonAlert.showMessage(commonFacade.bundle, "근태 종료시간이 시작시간 보다 작습니다.", null, "입력오류", view);
 					return ;
 				}
 				table.push(src);
 			}
 			var proxy:ReqWorkTimeProxy = facade.retrieveProxy(ReqWorkTimeProxy.NAME) as ReqWorkTimeProxy;
 			proxy.InsertWorkTime("2", table);
		}




		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Process MVC Messages
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		* 본 Class에서 처리해야할 Noti들을 등록한다.
		* 
		* @param
		* @return void
		*/
		override public function listNotificationInterests():Array 
		{
			return [
					TeamWorkTimeFacade.LOAD_PROFILE_COMPLETE,
					TeamWorkTimeFacade.LOAD_PROFILE_FAILED,
					TeamWorkTimeFacade.INSERT_REQ_VACATION_COMPLETE,
					TeamWorkTimeFacade.INSERT_REQ_VACATION_FAILED,
					TeamWorkTimeFacade.INSERT_REQ_WORKTIME_COMPLETE,
					TeamWorkTimeFacade.INSERT_REQ_WORKTIME_FAILED,
					TeamWorkTimeFacade.LOAD_VACATION_CODE_COMPLETE,
					TeamWorkTimeFacade.LOAD_VACATION_CODE_FAILED
					];
		}
		

		/**
		* Noti별로 처리한다.
		* 
		* @param
		* @return void
		*/
		override public function handleNotification(note:INotification):void
		{
			switch(note.getName()) 
			{
				case TeamWorkTimeFacade.LOAD_PROFILE_COMPLETE:
					//view.selectedMember = (note.getBody() as ProfileProxy).profile;
					break;
				case TeamWorkTimeFacade.LOAD_VACATION_CODE_COMPLETE:
					view.vacationCodeList = (note.getBody() as VacationCodeProxy).vacationList;
					view.worktimeCodeList = (note.getBody() as VacationCodeProxy).worktimeList;
					break;
				case TeamWorkTimeFacade.INSERT_REQ_VACATION_COMPLETE:
					PopUpManager.removePopUp(view);
					break;
				case TeamWorkTimeFacade.INSERT_REQ_VACATION_FAILED:
					CommonAlert.showMessage(commonFacade.bundle, "휴가쿼터를 모두 사용하셨습니다. 더이상 휴가를 등록할 수 없습니다.", null, "확인", view);
					break;
				case TeamWorkTimeFacade.INSERT_REQ_WORKTIME_COMPLETE:
					PopUpManager.removePopUp(view);
					break;
				case TeamWorkTimeFacade.INSERT_REQ_WORKTIME_FAILED:
					CommonAlert.showMessage(commonFacade.bundle, "근태를 등록할 수 없습니다. 담당자에게 연락하십시오.", null, "확인", view);
					break;
				default:
					//trace(this.instanceID+"에서 처리 안된 Noti가 검출됨 : " + note.getBody());
					break;
			}
		}
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Utility Functions
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
        private function get view():ReqForOthersView
        {
            return viewComponent as ReqForOthersView;
        }
	}
}